package com.kaede.hayate.security.jwt;

import com.kaede.hayate.common.constant.HttpMethod;
import com.kaede.hayate.security.entity.RestGrantedAuthority;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class AccessService {
    public boolean check(Authentication authentication, HttpServletRequest request) {
        for (GrantedAuthority grantedAuthority:authentication.getAuthorities()){
            if (grantedAuthority instanceof RestGrantedAuthority) {
                RestGrantedAuthority restGrantedAuthority = (RestGrantedAuthority) grantedAuthority;
                String url = restGrantedAuthority.getUrl();
                String method = restGrantedAuthority.getMethod();
                if (matchers(url, request)) {
                    if (method.equalsIgnoreCase(request.getMethod()) || HttpMethod.ALL.equalsIgnoreCase(method)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean matchers(String url, HttpServletRequest request) {
        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
        if (matcher.matches(request)) {
            return true;
        }
        return false;
    }
}
